import { useState, useCallback } from 'react';

import _lodash from 'lodash';

import { globalMessage } from '@/api';

export default function useGlobalMessage() {
  const [pageNum, setPageNum] = useState<number>(1);
  const changePage = useCallback((number: number) => {
    setPageNum(number);
  }, []);
  const [messageList, setMessageList] = useState<any[]>([]);
  const [messageHasNew, setMessageHasNew] = useState<boolean>(false);
  const [messageTotal, setMessageTotal] = useState<number>(0);

  const getMessageList = useCallback(async (params: { pageNo: number }) => {
    const result: any = await globalMessage.getPushList({
      ...params,
      pageSize: 12,
    });
    if (result && result.result) {
      const data = result.result;
      const records = data.records || [];
      const total = data.total || 0;
      const hasNew = _lodash.some(records, {
        status: '0',
      });
      const list = records.map((item: any) => ({
        ...item,
        key: item.id,
      }));
      setMessageHasNew(hasNew);
      setMessageTotal(total);
      setMessageList(list);
    } else {
      setMessageList([]);
    }
  }, []);

  const editMessage = useCallback(async (params: { id: string | number }) => {
    await globalMessage.editPush(params);
  }, []);

  return {
    pageNum,
    changePage,
    messageList,
    messageTotal,
    messageHasNew,
    getMessageList,
    editMessage,
  };
}
